package com.broada.apm.util;

import java.io.IOException;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;

/**
 * 
 * 
 * @author liss Create By 2014年11月25日 上午11:46:35
 */
public class JsonUtil {
	private ObjectMapper objectMapper;

	public static JsonUtil getInstance() {
		return new JsonUtil();
	}

	private JsonUtil() {
		objectMapper = new ObjectMapper();
		objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
		objectMapper.configure(SerializationFeature.INDENT_OUTPUT,true);
	}

	public JsonUtil filter(String filterName, String[] properties) {
		FilterProvider filterProvider = new SimpleFilterProvider().addFilter(filterName,
				SimpleBeanPropertyFilter.filterOutAllExcept(properties));
		objectMapper.setFilters(filterProvider);
		return this;
	}

	public JsonUtil addMixInAnnotations(Class<?> target, Class<?> mixinSource) {
		objectMapper.addMixInAnnotations(target, mixinSource);
		return this;
	}

	public JsonUtil setDateFormate(DateFormat dateFormat) {
		// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZ");
		// objectMapper.setDateFormat(sdf);
		return this;
	}

	public <T> T json2Obj(String json, Class<T> clazz) {
		try {
			return objectMapper.readValue(json, clazz);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("解析json错误");
		}
	}

	public String readAsString(Object obj) {
		try {
			return objectMapper.writeValueAsString(obj);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("解析对象错误");
		}
	}

	@SuppressWarnings("unchecked")
	public List<Map<String, Object>> json2List(String json) {
		try {
			return objectMapper.readValue(json, List.class);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("解析json错误");
		}
	}

	public <T> List<T> json2List(String json, Class<T> clazz) {
		List<Map<String, Object>> list;
		try {
			list = objectMapper.readValue(json, new TypeReference<List<T>>(){});
		} catch (IOException e) {
			throw new RuntimeException("解析json错误");
		}
		List<T> result = new ArrayList<T>();
		for (Map<String, Object> map : list) {
			result.add(map2pojo(map, clazz));
		}
		return result;
	}

	public <T> T map2pojo(Map map, Class<T> clazz) {
		return objectMapper.convertValue(map, clazz);
	}

	public ObjectMapper getObjectMapper() {
		return objectMapper;
	}

	public void setObjectMapper(ObjectMapper objectMapper) {
		this.objectMapper = objectMapper;
	}

}